package com.example.pilipili.exception;

import com.example.pilipili.common.R;
import jakarta.validation.ConstraintViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class MyExceptionHandler {

    // 登录校验
    @ExceptionHandler(value =NoLoginException.class)
    public R noLoginExceptionHandler(Exception e){
        return R.failed("请先登录") ;
    }
  // 数据校验
    @ExceptionHandler(value = ConstraintViolationException.class)
    public R defaultInsuranceExceptionHandler(ConstraintViolationException e) {
        return R.error("error", e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getDefaultMessage()).append("; ");
        }
        return R.error(null, String.valueOf(errorMessage)) ;
    }

    // 参数校验
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    public R handleMissingServletRequestParameter(MissingServletRequestParameterException ex) {
        String error = ex.getParameterName() + " 参数为空";
        return R.error("error", error);
    }


    @ExceptionHandler(value =Exception.class)
    public R exceptionHandler(Exception e){
        e.printStackTrace();
        return R.error("网络异常") ;
    }
}
